package com.vcc.web.controller;


import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckSafe;
import com.mybatisflex.core.paginate.Page;
import com.vcc.core.annotations.RepeatSubmit;
import com.vcc.core.annotations.RestPack;
import com.vcc.core.exception.NotFoundException;
import com.vcc.core.exception.ProgramException;
import com.vcc.data.entity.CardGroup;
import com.vcc.data.entity.Role;
import com.vcc.data.entity.User;
import com.vcc.service.client.dto.cardGroup.CardGroupTransferDto;
import com.vcc.service.client.dto.cardGroup.CreateCardGroupDto;
import com.vcc.service.client.dto.cardGroup.UpdateCardGroupDto;
import com.vcc.service.client.vo.cardGroup.CardGroupVo;
import com.vcc.service.service.CardGroupService;
import com.vcc.service.service.UserCardService;
import com.vcc.service.service.UserService;
import com.vcc.web.core.util.UserUtil;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("cardGroup")
public class CardGroupController {


    @Resource
    private CardGroupService cardGroupService;
    @Resource
    private UserCardService userCardService;
    @Resource
    private UserService userService;


    @PostMapping("create")
    @SaCheckLogin
    @SaCheckPermission("card-group:list:create")
    @RestPack
    @RepeatSubmit
    public Boolean create(@RequestBody @Validated CreateCardGroupDto createCardGroupDto) {
        Long id = UserUtil.getId();
        if (cardGroupService.existsByNameAndUserId(id, createCardGroupDto.getName())) {
            throw new IllegalArgumentException("卡组名称已存在");
        }
        CardGroup cardGroup = new CardGroup();
        cardGroup.setUserId(id);
        cardGroup.setName(createCardGroupDto.getName());
        cardGroup.setSort(cardGroup.getSort());
        cardGroup.setDescription(createCardGroupDto.getDescription());
        cardGroup.setStatus(0);
        cardGroup.setHasDefault(false);
        cardGroupService.save(cardGroup);
        return true;
    }

    @RestPack
    @GetMapping("paging")
    @SaCheckLogin
    @SaCheckPermission("card-group:list:view")
    public Page<CardGroupVo> paging(
            Integer pageNumber,
            Integer pageSize,
            Long targetUserId,
            String name,
            Integer status
    ) {
        return cardGroupService.clientPaging(
                pageNumber,
                pageSize,
                UserUtil.getRole(),
                targetUserId,
                UserUtil.getId(),
                name,
                status
        );
    }

    @PostMapping("update")
    @SaCheckLogin
    @SaCheckPermission("card-group:list:edit")
    @RestPack
    @RepeatSubmit
    public Boolean update(@RequestBody @Validated UpdateCardGroupDto updateCardGroupDto) {
        if (updateCardGroupDto.getStatus() != null && updateCardGroupDto.getStatus() == 1) {
            //关闭卡组时需要检查是否存在卡
            if (userCardService.countByCardGroupId(updateCardGroupDto.getId()) > 0) {
                throw new IllegalArgumentException("卡组内存在卡片，无法关闭");
            }
        }
        return cardGroupService.update(updateCardGroupDto, UserUtil.getId());
    }

    @PostMapping("transferCard")
    @SaCheckLogin
    @SaCheckPermission("card-group:list:edit")
    @RestPack
    @RepeatSubmit
    @SaCheckSafe("GROUP_TRANSFER_USER_CARD")
    public Boolean transferCard(@RequestBody @Validated CardGroupTransferDto cardGroupTransferDto) {
        Long userId = UserUtil.getId();
        CardGroup cardGroup = cardGroupService.getByIdOpt(cardGroupTransferDto.getSourceId()).orElseThrow(() -> new NotFoundException("源卡组不存在"));
        if (!cardGroup.getUserId().equals(userId)) {
            throw new ProgramException("非法操作");
        }
        CardGroup targetCardGroup = cardGroupService.getByIdOpt(cardGroupTransferDto.getTargetId()).orElseThrow(() -> new NotFoundException("目标卡组不存在"));
        if (!targetCardGroup.getUserId().equals(userId)) {
            throw new ProgramException("非法操作");
        }
        Long count = userCardService.countByCardGroupId(cardGroupTransferDto.getSourceId());
        if (count == 0) {
            throw new ProgramException("源卡组内没有卡片，无法转移");
        }
        return userCardService.updateCardGroupId(cardGroupTransferDto.getSourceId(), cardGroupTransferDto.getTargetId());
    }

    @GetMapping("listByName")
    @SaCheckLogin
    @SaCheckPermission("card-group:list:view")
    @RestPack
    public List<CardGroupVo> listByName(String name) {
        return cardGroupService.listByName(
                UserUtil.getId(),
                UserUtil.getRole(),
                name
        );
    }


    @GetMapping("listByNameAndUserId")
    @SaCheckLogin
    @SaCheckPermission("card-group:list:view")
    @RestPack
    public List<CardGroupVo> listByNameAndUserId(String name, Long targetUserId) {
        if (targetUserId == null || targetUserId <= 0) {
            throw new ProgramException("用户ID不能为空");
        }
        Role role = UserUtil.getRole();
        User user = UserUtil.get();

        UserUtil.baseVerifyUser(
                role,
                user.getId(),
                targetUserId,
                user.getParentId(),
                userService.getParentIdById(targetUserId)
        );
        return cardGroupService.listByName(
                user.getId(),
                role,
                name,
                targetUserId
        );
    }
}
